$(document).ready(function(id) {
    
    //    $('#objects').leftScrollbar(); 
    
    var count_dropped_hits = 0;
    var data = {
        "images": [
        {
            "id" : "obj_0" ,
            "src" : $('#obj_0').attr('src')	,
            "width" : $('#obj_0').attr('width'), 
            "height" : $('#obj_0').attr('height')
        }
        ]
    };
    // Array Remove - By John Resig (MIT Licensed)
    Array.prototype.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
    };
				
    /*  remove an object from data */
    $('.remove',$('#tools')).live('click',function(){
        var $this = $(this);
					
        /* the element next to this is the input that stores the obj id */
        var objid = $this.next().val();
        /* remove the object from the sidebar */
        $this.parent().remove();
        /* ,from the picture */
        var divwrapper = $('#'+objid).parent().parent();
        $('#'+objid).remove();
        /* add again to the objects list */
        var image_elem 		= $this.parent().find('img');
        var thumb_width 	= image_elem.attr('width');
        var thumb_height 	= image_elem.attr('height');
        var thumb_src 		= image_elem.attr('src');
        $('<img/>',{
            id 			: 	objid,
            src			: 	thumb_src,
            width		:	thumb_width, 
            //height		:	thumb_height,
            className	:	'ui-widget-content'
        }).appendTo(divwrapper).resizable({
            handles	: 'se',
            stop	: resizestop 
        }).parent('.ui-wrapper').draggable({
            revert: 'invalid'
        });
        /* and unregister it - delete from object data */
        var index = exist_object(objid);
        data.images.remove(index);
    });
                
    /*  checks if an object was already registered */
    function exist_object(id){
        for(var i = 0;i<data.images.length;++i){
            if(data.images[i].id == id)
                return i;
        }
        return -1;
    }
				
    /* triggered when stop resizing an object */
    function resizestop(event, ui) {
        //calculate and change values to obj (width and height)
        var $this 		= $(this);
        var objid		= $this.find('.ui-widget-content').attr('id');
        var objwidth            = ui.size.width;
        var objheight           = ui.size.height;
				
        var index 		= exist_object(objid);
				
        if(index!=-1) { //if exists (it should!) update width and height
            data.images[index].width 	= objwidth;
            data.images[index].height 	= objheight;
        }
    }
    makeObjAction();
    $('#background').droppable({
        accept	: '.obj_item div', /* accept only draggables from #objects */
        drop	: function(event, ui) {
            var $this 		= $(this);
            dropCallback($this,event,ui);
        }
    });
			
    /* User presses the download button */
    $('#submit').bind('click',function(){
        var dataString  = JSON.stringify(data);
        $.ajax({
            type: "POST",
            url: "/process.php",
            data: "action=member_edit_iamge&jsondata="+dataString,
            dataType: 'json',
            success: function(msg){
                if(msg.status=='ok'){
                    history.go(-1);
                }
            }
        });
    });
    //    $("#content").click(function(){
    //        $('.item_layer').each(function(){
    //            if($(this).ismouseover())
    //            {
    //                $(this).addClass("active");  
    //                $(this).find('.ui-resizable-handle').css("display","block");
    //            }
    //            else
    //            {
    //                $(this).removeClass("active");
    //                $(this).find('.ui-resizable-handle').css("display","none");
    //            }
    //        })
    //    })

    $("#obj_0").bind( "mousedown", function(event) {  
        $('.item_layer').each(function(){
            if($(this).ismouseover() && $(this).find('.obj_item').length>0 ){
                $(this).addClass("active");  
                $(this).find('.ui-resizable-handle').css("display","block");      
                var draggable_elem= $(this).find('.ui-draggable');
                draggable_elem.trigger(event);
                $(document).keydown(function(event){  
                    if (event.which != 0){
                        switch(event.which){
                            case 13:
                                
                            case 39:
                                moveright(draggable_elem);
                                break;
                            case 37:
                                moveleft(draggable_elem);
                                break;
                            case 38:
                                moveup(draggable_elem);
                                break;
                            case 40:
                                movedown(draggable_elem);
                                break;
 
                        }
                    }
                });
            }
            else
            {
                $(this).removeClass("active");
                $(this).find('.ui-resizable-handle').css("display","none");               
            }
        })
    });
    function moveleft(obj){
        var xpos=parseInt(obj.position().left)-10;
        obj.css('left',xpos +"px");
    }
 
    function moveright(obj){
        var xpos=parseInt(obj.position().left)+10;
        obj.css('left',xpos +"px");
    }
    function moveup(obj){
        var ypos=parseInt(obj.position().top)-10;
        obj.css('top',ypos +"px");
    }
    function movedown(obj){
        var ypos=parseInt(obj.position().top)+10;
        obj.css('top',ypos +"px");
    }

    jQuery.mlp = {
        x:0,
        y:0
    }; // Mouse Last Position
    $(document).mousemove(function(e){
        jQuery.mlp = {
            x:e.pageX,
            y:e.pageY
        }
    });
    function notNans(value){
        if(isNaN(value)){
            return 0;
        } else {
            return value
        }
    }
    $.fn.ismouseover = function(overThis) {  
        var result;
        this.eq(0).each(function() {  
            var offSet = $(this).offset();
            var w = Number($(this).width())
            + notNans(Number($(this).css("padding-left").replace("px","")))
            + notNans(Number($(this).css("padding-right").replace("px",""))) 
            + notNans(Number($(this).css("border-right-width").replace("px","")))
            + notNans(Number($(this).css("border-left-width").replace("px",""))) ;
            var h = Number($(this).height()) 
            + notNans(Number($(this).css("padding-top").replace("px",""))) 
            + notNans(Number($(this).css("padding-bottom").replace("px","")))
            + notNans(Number($(this).css("border-top-width").replace("px","")))
            + notNans(Number($(this).css("border-bottom-width").replace("px","")));
            if(offSet.left<jQuery.mlp.x && offSet.left + w > jQuery.mlp.x
                && offSet.top<jQuery.mlp.y &&  offSet.top + h > jQuery.mlp.y)
                {
                result = true;
            } else {
                result = false;
            }
        });  
        return result;
    };  
       
    $(".loadImg").filter(":visible").each(function(){
        var objid=$(this).attr("id");  
        var arr=objid.split('_');
        var temp=objid;
        upclick(
        {
            element: window.document.getElementById(objid),
            action: '/process.php?action=upload_card_temp', 
            onstart:
            function(filename)
            {
           
            },
            oncomplete:
            function(response_data) 
            {
                if(response_data!="false")
                {
                    var obj=$("#"+temp);                   
                    var frameDimensions=obj.attr('rel').split("_");
                    var jsonObject = jQuery.parseJSON(response_data);
                    var height=frameDimensions[0];
                    var width=height*jsonObject.width/jsonObject.height;
                    if(width<frameDimensions[1])
                    {
                        width= frameDimensions[1];
                        height= jsonObject.height / jsonObject.width * width;
                    }
                    var dimensions="height:"+height+"px;width:"+width+"px"; 
                    var aspectRatio=width/height;
                    var posx=obj.position().left-Math.round((width-obj.width())/2);
                    var posy=obj.position().top-Math.round((height-obj.height())/2);
                    var html='<div class="obj_item" style="position:absolute;top:'+posy.toString()+'px;left:'+posx.toString()+'px;" ><img id="obj_'+arr[1].toString()+'" style="'+dimensions+';" src="'+jsonObject.filename+'" /></div>';
                    obj.parent().append(html);
                    /* objects are resizable and draggable */
                    makeObjAction(aspectRatio);
                    obj.hide();
                    var elem            = obj.parent().find(".obj_item");
                    var objsrc          = elem.find('.ui-widget-content').attr('src');
                    var objwidth 	= parseFloat(elem);
                    var objheight 	= parseFloat(elem.width);
					
                    /* for top and left we decrease the top and left of the droppable element */
                    var objtop		= elem.offset().top;
                    var objleft		= elem.offset().left;
                                       
                    var objid		= elem.find('.ui-widget-content').attr('id');
                    /* register new one */
                    var newObject = { 
                        'id' 		: objid,
                        'src' 		: objsrc,
                        'width' 	: objwidth,
                        'height' 	: objheight,
                        'top' 		: objtop,
                        'left' 		: objleft,
                        'rotation'      : '0'
                    };
                    data.images.push(newObject);
                   
                }
            }
        });
    })
    
    function makeObjAction($aspectRatio) {        
        $('.obj_item img').resizable({
            aspectRatio: $aspectRatio,
            handles: 'ne, se, sw, nw' ,
            stop	: resizestop 
        }).parent('.ui-wrapper') .draggable({
            revert	: 'invalid'
        });
        $('.ui-wrapper').transformable({
            scalable:false, 
            skewable:false,
            stop: function(event, ui) {
                newObject.rotation = ui.value;
                var $this 		= $(this);
                var objid		= $this.find('.ui-widget-content').attr('id');
                var objrotate           = ui.attr('rotate');               
                var index 		= exist_object(objid);
                if(index!=-1) { //if exists (it should!) update width and height
                    data.images[index].rotation 	= objrotate;
                }
            }
        });	
        $(".ui-resizable-handle").css("display","none");
    }; 
    function dropCallback($this,event,ui)
    {
        $('.item_layer').removeClass("active");
        $('.ui-resizable-handle').css("display","none");   
        ++count_dropped_hits;
        var draggable_elem = ui.draggable;
        // draggable_elem.css('z-index',count_dropped_hits);
        /* object was dropped : register it */
        var objsrc 	= draggable_elem.find('.ui-widget-content').attr('src');
        var objwidth 	= parseFloat(draggable_elem);
        var objheight 	= parseFloat(draggable_elem.width);
					
        /* for top and left we decrease the top and left of the droppable element */
        var objtop		= ui.offset.top - $this.offset().top;
        var objleft		= ui.offset.left - $this.offset().left;
                                       
        var objid		= draggable_elem.find('.ui-widget-content').attr('id');
					
        var index 		= exist_object(objid);
						
        if(index!=-1) { //if exists update top and left
            data.images[index].top 	= objtop;
            data.images[index].left = objleft;
        }
        else{					
         		
           
            $('.slider').slider({
                orientation	: 'horizontal',
                max			: 180,
                min			: -180,
                value		: 0,
                slide		: function(event, ui) {
                    var $this = $(this);
                    /* Change the rotation and register that value in data object when it stops */
                    draggable_elem.css({
                        '-moz-transform':'rotate('+ui.value+'deg)',
                        '-webkit-transform':'rotate('+ui.value+'deg)'
                    });
                    $('.degrees',$this).html(ui.value);
                },
                stop		: function(event, ui) {
                    newObject.rotation = ui.value;
                }
            });	
        }
    };
       
    $('.template_item').click(function(){
        var $src=$(this).find('img').attr('src').replace("thumb/", "");
        var $id=$(this).find('img').attr('id');
        $('#obj_0').attr('src',$src);
        $('#background').attr('class','template_'+$id);
        $(".loadImg").removeAttr('style');
        $(".obj_item").remove();
        $(".loadImg").filter(":visible").each(function(){
            var objid=$(this).attr("id");
            var arr=objid.split('_');
        
            upclick(
            {
                element: objid,
                action: '/process.php?action=upload_card_temp', 
                onstart:
                function(filename)
                {
           
                },
                oncomplete:
                function(response_data) 
                {
                    if(response_data!="false")
                    {
                        var obj=$("#"+objid);
                        var frameDimensions=obj.attr('rel').split("_");
                        var jsonObject = jQuery.parseJSON(response_data);
                        var height=frameDimensions[0];
                        var width=height*jsonObject.width/jsonObject.height;
                        if(width<frameDimensions[1])
                        {
                            width= frameDimensions[1];
                            height= jsonObject.height / jsonObject.width * width;
                        }
                        var dimensions="height:"+height+"px;width:"+width+"px"; 
                        var aspectRatio=width/height;
                        var posx=obj.position().left-Math.round((width-obj.width())/2);
                        var posy=obj.position().top-Math.round((height-obj.height())/2);
                        var html='<div class="obj_item" style="position:absolute;top:'+posy.toString()+'px;left:'+posx.toString()+'px;" ><img id="obj_'+arr[1].toString()+'" style="'+dimensions+';" class="ui-widget-content" src="'+jsonObject.filename+'" /></div>';
                        obj.parent().append(html);
                        /* objects are resizable and draggable */
                        makeObjAction(aspectRatio);
                        obj.hide();
                    }
                }
            });
        })
    })
});